using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System.Collections;
using System.Collections.Specialized;

namespace WinUITest.Controls
{
    public partial class DistributedItemsControl : ItemsControl
    {
        private INotifyCollectionChanged? _currentCollection;

        public DistributedItemsControl()
        {
            Loaded += DistributedItemsControl_Loaded;
            Unloaded += DistributedItemsControl_Unloaded;
            RegisterPropertyChangedCallback(ItemsSourceProperty, OnItemsSourcePropertyChanged);
        }

        private void DistributedItemsControl_Unloaded(object sender, RoutedEventArgs e)
        {
            if (_currentCollection == null) return;
            _currentCollection.CollectionChanged -= Incc_CollectionChanged;
            _currentCollection = null;
        }

        private void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyProperty dp)
        {
            if (dp != ItemsSourceProperty) return;
            if (_currentCollection != null)
            {
                _currentCollection.CollectionChanged -= Incc_CollectionChanged;
                _currentCollection = null;
            }
            if (ItemsSource is INotifyCollectionChanged newIncc)
            {
                _currentCollection = newIncc;
                _currentCollection.CollectionChanged += Incc_CollectionChanged;
            }
            UpdateColumns();
        }

        private void DistributedItemsControl_Loaded(object sender, RoutedEventArgs e) => UpdateColumns();
        private void Incc_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => UpdateColumns();

        private void UpdateColumns()
        {
            if (ItemsPanelRoot is not Grid grid) return;
            grid.ColumnDefinitions.Clear();

            int count = 0;
            if (ItemsSource is ICollection collection)
            {
                count = collection.Count;
            }
            else if (Items != null)
            {
                count = Items.Count;
            }

            for (int i = 0; i < count; i++)
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            }
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            if (element is not FrameworkElement container) return;
            int index = IndexFromContainer(element);
            Grid.SetColumn(container, index);
        }
    }
}
